import Vue from 'vue'
import Vuex from 'vuex'
import persist from "vuex-persist"
import {
  Toast
} from 'vant';
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: [],
    shoplist: [],
  },
  mutations: {
    onSubmit(state, val) {
      state.user = val
    },
    // 添加购物车
    add(state, item) {
      let flag = false //代表此商品在购物车数据中是否存在
      state.shoplist.forEach(i => {
        // 当新添加的商品和已有商品id相同时，让数量加1
        if (i.product_id == item.product_id) {
          i.num++
          flag = true
          return false
        }
      })
      if (flag == false) {
        // 如果没有商品，添加一条
        Vue.set(item, "num", 1);
        state.shoplist.push(item)
        Toast('添加成功！');
      }
    },
    change(state, obj) {
      // 循环加入购物车的商品
      state.shoplist.forEach(item => {
        // 若购物车商品id等于传递过来的商品id时，
        // 把传递过来的商品数量赋值给购物车商品数量，实现加加减减功能
        if (item.product_id == obj.product_id) {
          item.num = obj.num
        }
      })
    },
    remove(state, i) {
      state.shoplist.forEach((item, index) => {
        if (item.product_id == i.product_id) {
          state.shoplist.splice(index, 1);
        }
      });
    },
    select(state, item) {
      state.shoplist.forEach((i) => {
        if (i.product_id == item.product_id) {
          i.choose = !i.choose
        }
      })
      localStorage.setItem("shoplist", JSON.stringify(state.shoplist))
    },
    allChoose(state, val) {
      state.shoplist.forEach((i) => {
        i.choose = val
      })
      localStorage.setItem("shoplist", JSON.stringify(state.shoplist))
    },
  },
  actions: {},
  modules: {},
  getters:{
    
  },
  plugins: [
    new persist({
      storage: window.localStorage,
    }).plugin,
  ],
})